<script setup lang="ts">
  import ApplyModal from './ApplyModal.vue'
  import CheckParts from './CheckModal.vue'
  import { PropType, ref } from 'vue'
  import DetailModal from './DetailModal.vue'
  import { useUserStore } from '@/store/modules/user'
  import { useGetMaterialListByOrderId } from '@/services/pages/order/useSpare'
  import { TableColumnCtx } from 'element-plus'
  import { useRouter } from 'vue-router'
  import { useGetWarehouseOutList } from '@/services/pages/storage/useWarehouseOut'

  const { list: outBoundList, getListParam, getList: getBoundList } = useGetWarehouseOutList()
  const { list, listTotal, getList } = useGetMaterialListByOrderId()

  const props = defineProps({
    orderDetail: {
      type: Object as PropType<OrderDetail>,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'updated'): void
  }>()

  // 全局路由对象
  const router = useRouter()

  // 客户状态管理
  const userStore = useUserStore()

  // 新增配件费用弹窗状态
  const addPartsModalVisible = ref(false)

  // 配件id
  const partsId = ref('')

  // 配件审核弹窗状态
  const checkPartsModalVisible = ref(false)

  // 弹窗的类型 1审核   2编辑
  const modalType = ref(1)

  // 配件审核事件
  const handlePartCheck = (id: string) => {
    modalType.value = 1
    partsId.value = id
    checkPartsModalVisible.value = true
  }

  // 配件详情弹窗状态
  const partsDetailModalVisible = ref(false)

  // 查看费用详细
  const handleViewPartsDetail = (n: string) => {
    partsDetailModalVisible.value = true
    partsId.value = n
  }

  /**
   * 列表更新事件
   */
  const onUpdateTableData = () => {
    getList(props.orderDetail.id)
    emits('updated')
  }

  /**
   * 表格合计回调
   * @param param - 回调参数
   */
  const getSummaries = (param: {
    columns: TableColumnCtx<OrderMaterial>[]
    data: Array<OrderMaterial>
  }) => {
    const arr = [
      'number',
      'priceTotal',
      'customerUndertakePriceTotal',
      'networkUndertakePriceTotal',
    ]
    const { columns, data } = param

    const sums: string[] = []
    columns.forEach((column, index) => {
      if (index == 0) {
        sums[index] = '合计'
        return
      }

      if (!arr.includes(column.property)) {
        return
      }

      const values = data.map((item) => Number(item[column.property as keyof OrderMaterial]) || 0)

      if (!values.every((value) => Number.isNaN(value))) {
        const valuesTotal = values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!Number.isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        }, 0)
        if (column.property === 'number') {
          sums[index] = valuesTotal.toString()
        } else {
          sums[index] = `￥${valuesTotal.toFixed(2)}`
        }
      } else {
        sums[index] = ''
      }
    })
    return sums
  }

  /**
   * 出库单号点击事件
   * @param sparePart - 配件对象
   */
  const handleOutBoundCodeClick = async (sparePart: OrderMaterial) => {
    if (sparePart.storeOutboundCode) {
      getListParam.value.search = sparePart.storeOutboundCode
      await getBoundList()
      const outBound = outBoundList.value[0]
      if (outBound) {
        if (outBound.status == 1) {
          router.push(`/storage/newout/${sparePart.storeOutboundId}/${2}`)
        } else {
          router.push('/storage/outb/detail/' + sparePart.storeOutboundId)
        }
      }
    }
  }

  defineExpose({
    getList,
  })
</script>

<template>
  <div class="order-spare-part-list">
    <div class="title">
      工单配件({{ listTotal }})
      <h-plain-button
        v-if="props.orderDetail.status === 3"
        :padding-lr="6"
        :height="22"
        @click="addPartsModalVisible = true"
      >
        申请配件
      </h-plain-button>
    </div>

    <el-table
      resizable
      :data="list"
      stripe
      style="width: 100%"
      :border="true"
      :max-height="300"
      show-summary
      :summary-method="getSummaries"
    >
      <!-- 序号 -->
      <el-table-column label="序号" fixed="left" width="50" :align="'center'" type="index" />

      <!-- 状态 -->
      <el-table-column prop="state" label="状态" width="83" fixed="right" :align="'center'">
        <template #default="{ row }">
          <div class="flex_justify_center">
            <h-status v-if="row.status === 1" type="warning">待审核</h-status>
            <h-status v-if="row.status === 2" type="success">已通过</h-status>
            <h-status v-if="row.status === 3" type="error">已驳回</h-status>
            <h-status v-if="row.status === 4" type="warning">已撒回</h-status>
            <h-status v-if="row.status === 5" type="info">已取消</h-status>
          </div>
        </template>
      </el-table-column>

      <!-- 申请类型 -->
      <el-table-column show-overflow-tooltip prop="type" label="申请类型" width="80" />

      <!-- 出库单号 -->
      <el-table-column show-overflow-tooltip prop="storeOutboundCode" label="出库单号" width="120">
        <template #default="{ row }">
          <h-link @click="handleOutBoundCodeClick(row)">{{ row.storeOutboundCode }}</h-link>
        </template>
      </el-table-column>

      <!-- 配件单号 -->
      <el-table-column show-overflow-tooltip prop="code" label="配件单号" width="140">
        <template #default="{ row }">
          <span class="number" @click="handleViewPartsDetail(row.id)">
            {{ row.code }}
          </span>
        </template>
      </el-table-column>

      <!-- 配件名称 -->
      <el-table-column show-overflow-tooltip prop="name" label="配件名称" width="160" />

      <!-- 配件编号 -->
      <el-table-column show-overflow-tooltip prop="goodsCode" label="配件编号" width="100" />

      <!-- 旧件处理方式 -->
      <el-table-column show-overflow-tooltip label="旧件处理方式" width="100">
        <template #default="{ row }">
          {{ row.oldCopeWay == 1 ? '废弃' : row.oldCopeWay == 2 ? '旧件退回' : '' }}
        </template>
      </el-table-column>

      <!-- 数量 -->
      <el-table-column prop="number" label="数量" width="50" />

      <!-- 公司承担单价 -->
      <el-table-column
        v-if="!userStore.isCurrentRoleNetwork"
        prop="price"
        label="公司承担单价"
        width="100"
      >
        <template #default="{ row }"> ￥{{ (row.price || 0).toFixed(2) }} </template>
      </el-table-column>

      <!-- 收取客户单价 -->
      <el-table-column
        v-if="!userStore.isCurrentRoleNetwork"
        show-overflow-tooltip
        prop="customerUndertakePrice"
        label="收取客户单价"
        width="100"
      >
        <template #default="{ row }">
          ￥{{ (row.customerUndertakePrice || 0).toFixed(2) }}
        </template>
      </el-table-column>

      <!-- 支付网点单价 -->
      <el-table-column
        show-overflow-tooltip
        prop="networkUndertakePrice"
        label="支付网点单价"
        width="100"
      >
        <template #default="{ row }">
          ￥{{ (row.networkUndertakePrice || 0).toFixed(2) }}
        </template>
      </el-table-column>

      <!-- 公司承担总费用 -->
      <el-table-column
        v-if="!userStore.isCurrentRoleNetwork"
        prop="priceTotal"
        label="公司承担总费用"
        width="120"
      >
        <template #default="{ row }"> ￥{{ (row.priceTotal || 0).toFixed(2) }} </template>
      </el-table-column>

      <!-- 收取客户总费用 -->
      <el-table-column
        v-if="!userStore.isCurrentRoleNetwork"
        prop="customerUndertakePriceTotal"
        label="收取客户总费用"
        width="120"
      >
        <template #default="{ row }">
          ￥{{ (row.customerUndertakePriceTotal || 0).toFixed(2) }}
        </template>
      </el-table-column>

      <!-- 支付网点总费用 -->
      <el-table-column prop="networkUndertakePriceTotal" label="支付网点总费用" width="120">
        <template #default="{ row }">
          ￥{{ (row.networkUndertakePriceTotal || 0).toFixed(2) }}
        </template>
      </el-table-column>

      <!-- 申请人员 -->
      <el-table-column show-overflow-tooltip prop="applyEmp" label="申请人员" width="120" />

      <!-- 申请时间 -->
      <el-table-column prop="createTime" label="申请时间" width="128" />

      <!-- 审核人员 -->
      <el-table-column show-overflow-tooltip prop="reviewEmp" label="审核人员" width="80" />

      <!-- 审批时间 -->
      <el-table-column prop="reviewTime" label="审批时间" width="128" />

      <!-- 操作 -->
      <el-table-column label="操作" width="50" fixed="right">
        <template #default="{ row }">
          <div v-permission="'order_review_product'" class="ord_dis">
            <h-link v-if="row.status == 1" @click="handlePartCheck(row.id)">审核</h-link>
            <h-link v-else disabled type="info">审核</h-link>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 审核/编辑配件 -->
    <CheckParts
      v-model="checkPartsModalVisible"
      :order-detail="props.orderDetail"
      :parts-id="partsId"
      @update-list="onUpdateTableData"
    />

    <!-- 查看详细弹出框 -->
    <DetailModal v-model="partsDetailModalVisible" :parts-id="partsId" />

    <!-- 配件申请弹窗 -->
    <apply-modal
      v-model="addPartsModalVisible"
      :order-detail="props.orderDetail"
      @update-list="onUpdateTableData"
    />
  </div>
</template>

<style scoped lang="scss">
  .order-spare-part-list {
    display: flex;
    flex-direction: column;
    background-color: #fff;
    padding: 12px;
    box-sizing: border-box;
    row-gap: 8px;

    .title {
      font-size: 14px;
      font-weight: bold;
      padding-left: 6px;
      border-left: 3px solid #007cff;
      display: flex;
      align-items: center;
      column-gap: 4px;
    }

    .footer {
      display: flex;
      justify-content: flex-end;
    }
  }
</style>
